package com.naiterui.ehp.bp.support.mvc;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Type;

import org.apache.commons.lang3.StringUtils;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.lang.NonNull;
import org.springframework.util.Assert;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

/**
 * RequestObject 注解解析类，如果在spring mvc 中使用此注解，会将传递过来的参数（json)转化为实体
 *
 * @author wangzehao
 * @date 2018/11/19 5:14 PM
 * @since 1.0.0
 */
public class RequestObjectArgResolverHandler implements HandlerMethodArgumentResolver {

    private MappingJackson2HttpMessageConverter messageConverter;

    public RequestObjectArgResolverHandler(MappingJackson2HttpMessageConverter messageConverter) {
        Assert.notNull(messageConverter, "messageConverter 不能为null");
        this.messageConverter = messageConverter;
    }

    @Override
    public boolean supportsParameter(@NonNull MethodParameter methodParameter) {
        return methodParameter.hasParameterAnnotation(RequestObject.class);
    }

    @Override
    public Object resolveArgument(@NonNull MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer,
                                  @NonNull NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws IOException {

        // 获取Controller中的参数名
        String parameterName = methodParameter.getParameterName();
        // 获取Controller中参数的类型
        Type type = methodParameter.getGenericParameterType();
        String parameter = nativeWebRequest.getParameter(parameterName);
        //如果没有传参数，则返回null
        if (StringUtils.isEmpty(parameter)) {
            return null;
        }
        // 这里转换json
        return this.messageConverter.read(type, null, new HttpInputMessage() {
            @Override
            public InputStream getBody() {
                return new ByteArrayInputStream(parameter.getBytes());
            }

            @Override
            public HttpHeaders getHeaders() {
                return new HttpHeaders();
            }
        });

    }
}